package cn.itsource.interceptor;

import cn.itsource.annotation.CheckPer;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Component
public class CheckPermission implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进去权限拦截器了");
        //hander可以理解为请求对象
        if(!(handler instanceof HandlerMethod)){
            //说明拦截到不是请求方法是静态资源
            return true; //放行
        }
        //到这里说明是方法
        HandlerMethod handlerMethod= (HandlerMethod) handler;
        //获取目标方法对象
        Method method = handlerMethod.getMethod();
        //获取目标方法是的注解
        CheckPer annotation = method.getAnnotation(CheckPer.class);
        if(annotation==null){
            System.out.println("直接放行了");
            return true;
        }
        //获取说明的权限字符串
        String per = annotation.per();
        //判断token
        String token = request.getHeader("token");
        //没有token就直接去前端
        //拿权限
        //List<String> list=redis.get(token);
        ArrayList<String> strings = new ArrayList<>();
        strings.add("user:add");
        strings.add("user:delete");
        strings.add("user:update");
        if(!strings.contains(per)){
            System.out.println("没有权限访问接口");
            return false;//拦截
        }
        System.out.println("有权限访问接口");
        return true;
    }
}
